<template>
  <!-- 新增预约 -->
  <section class="add-reserve">
    <div class="flex-gutter">
      <div class="flex-left">
        <h3>患者信息</h3>
        <div class="form-tool">
          <div>
            <el-form label-width="100px" label-position="top" ref="form" :model="form" :rules="rules">
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item label="患者：" prop="patientId">
                    <el-select
                      v-model.trim="form.patientId"
                      default-first-option
                      allow-create
                      filterable
                      remote
                      clearable
                      @clear="onClearPatient"
                      :remote-method="getPatient"
                      @change="onChangePatient"
                    >
                      <el-option
                        v-for="(item, index) in patientArray"
                        :key="index"
                        :value="item.patientId"
                        :label="item.name + '（' + item.mobil + '）'"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="证件号：" prop="idCard" :rules="[form.certificateType == 1 ? rulesIdCard : {}]">
                    <el-input v-model="form.idCard" @blur="onBlurIdCard">
                      <el-select v-model="form.certificateType" style="width:100px;" slot="prepend" placeholder="请选择">
                        <el-option v-for="(item, index) in certificateTypeArray" :key="index" :label="item.desc" :value="item.id"></el-option>
                      </el-select>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="出生年月：" prop="birthday">
                    <el-date-picker v-model="form.birthday" value-format="yyyy-MM-dd" type="date" @change="onChangeBirthday"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="年龄：" prop="age">
                    <el-input v-model.number="form.age"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="性别：" prop="sex">
                    <el-radio-group v-model="form.sex">
                      <el-radio :label="1">男</el-radio>
                      <el-radio :label="2">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="手机号：" prop="mobile">
                    <el-input v-model="form.mobile"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="国籍：" prop="nationalityId">
                    <el-select v-model="form.nationalityId">
                      <el-option v-for="(item, index) in nationalityEnum" :key="index" :value="item.id" :label="item.desc"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="6">
                  <el-form-item label="微信号：" prop="openId">
                    <el-input v-model="form.openId"></el-input>
                  </el-form-item>
                </el-col>-->
                <el-col :span="8">
                  <el-form-item label="省市区：" prop="areaArray">
                    <!-- <v-area v-model="form.areaArray" :isFull="true"></v-area> -->
                    <cascaderCity v-model="form.areaArray"></cascaderCity>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="详细地址：" prop="address">
                    <el-input v-model="form.address"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="职业：" prop="occupationId">
                    <el-select v-model="form.occupationId" clearable>
                      <el-option v-for="(item, index) in occupationArray" :key="index" :value="item.id" :label="item.desc"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="民族：" prop="nationId">
                    <el-select v-model="form.nationId" clearable>
                      <el-option v-for="(item, index) in nationArray" :key="index" :value="item.id" :label="item.desc"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="工作单位：" prop="workUnit">
                    <el-input v-model="form.workUnit"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="婚姻状况：" prop="isMarried">
                    <el-radio-group v-model="form.isMarried">
                      <el-radio :label="1">已婚</el-radio>
                      <el-radio :label="0">未婚</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="推荐来源：" prop="sourceType">
                    <el-select v-model="form.sourceType" clearable @change="onChangeTJ">
                      <el-option v-for="item in sourceArray" :key="item.id" :value="item.id" :label="item.desc"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="推荐详情：" prop="sourceName" :rules="[{ required: true, message: '请选择推荐详情', trigger: 'change' }]">
                    <doctorSearch v-if="form.sourceType == 1" ref="tjDoc" v-model="form.sourceCode" @change="onTCDoctor"></doctorSearch>
                    <el-select
                      v-else-if="form.sourceType == 2 || form.sourceType == 3 || form.sourceType == 4"
                      value-key="id"
                      v-model="sourceObj"
                      placeholder="请选择"
                      @change="onChangeSourceObj"
                    >
                      <el-option v-for="item in sourceObjList" :key="item.id" :label="item.name" :value="item"></el-option>
                    </el-select>
                    <el-input v-else v-model="form.sourceName"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <h3>科室信息</h3>
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-form-item label="预约科室：" prop="deptId">
                    <deptSearch v-model="form.deptId" @change="onChangeDept"></deptSearch>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="预约医生：" prop="doctorId">
                    <doctorSearch ref="doctorSearch" v-model="form.doctorId" :deptId="form.deptId"></doctorSearch>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="预约类型：" prop="registerType">
                    <el-select v-model="form.registerType" clearable>
                      <el-option v-for="(item, index) in reserveTypeArray" :key="index" :value="item.id" :label="item.desc"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="预约时间：" prop="timeId">
                    <el-input :value="form.timeStr" @focus="onOpenTime"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="预约内容：" prop="registerContent">
                    <el-input v-model="form.registerContent"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="看诊时间：">
                    <el-time-select
                      v-model="form.smsVisitTime"
                      :picker-options="{
                        start: '07:00',
                        step: '00:15',
                        end: '22:00'
                      }"
                      placeholder="请选择看诊时间"
                    >
                    </el-time-select>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="预约内容：">
                    <el-checkbox v-model="form.smsSend">发送短信通知</el-checkbox>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item style="margin-top:15px;">
                <el-button :disabled="!qxBtns.add" type="primary" @click="onSubmit">保存</el-button>
                <el-button @click="formReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <reserveTime v-model="dialogTime" :deptId="form.deptId" :doctorId="form.doctorId" @confirm="onConfirmTime"></reserveTime>
      </div>
      <div class="flex-right">
        <h3>今日预约</h3>
        <reservePatient></reservePatient>
      </div>
    </div>
  </section>
</template>
<script>
import validate from "@/_js/validate.js";
export default {
  props: ["qxBtns"],
  components: {
    oneImageUpload: () => import("@/components/oneImageUpload.vue"),
    "v-area": () => import("@/components/area.vue"),
    cascaderCity: () => import("@/components/cascaderCity.vue"),
    reserveTime: () => import("../_com/reserveTime.vue"),
    deptSearch: () => import("@/pages/_com/deptSearch.vue"),
    doctorSearch: () => import("@/pages/_com/newSearchDoctor.vue"),
    reservePatient: () => import("./reservePatientForNewRes.vue")
  },
  data() {
    return {
      btnLoading: false,
      dialogTime: false,
      upFileLoading: false,
      form: {
        id: "",
        timeId: "",
        name: "",
        registerType: "",
        registerContent: "",
        registerName: "",
        sourcePass: "",
        patientId: "",
        birthday: "",
        age: "",
        head: "",
        sex: 1,
        mobile: "",
        idCard: "",
        isMarried: 0,
        nationId: "",
        occupationId: "",
        workUnit: "",
        openId: "",
        provinceId: "",
        province: "",
        cityId: "",
        city: "",
        districtId: "",
        district: "",
        address: "",
        nationalityId: 1,
        type: 1,
        deptId: "",
        doctorId: "",
        source: "",
        sourceName: "",
        sourceId: "",
        sourceType: "",
        sourceCode: "",
        dateDay: "",
        certificateType: 1,
        medicalCardCode: "",
        email: "",
        tjDoctorId: null,
        areaArray: [],
        timeStr: "",
        smsSend: false,
        smsVisitTime: ""
      },
      doctorArray: [],
      deptArray: [],
      reserveTypeArray: [],
      sourceArray: [],
      sourceObj: null,
      sourceObjList: [],
      nationArray: [],
      jgEnum: [],
      ptEnum: [],
      occupationArray: [],
      patientArray: [],
      nationalityEnum: [],
      certificateTypeArray: [],
      rulesIdCard: { validator: validate.vPeopleNumber, trigger: "blur" },
      rules: {
        patientId: [
          { required: true, message: "此项必填", trigger: "change" },
          { validator: validate.verigySpacing, trigger: ["change", "blur"] }
        ],
        registerType: [{ required: true, message: "此项必填", trigger: "blur" }],
        age: [{ validator: validate.integerNum, trigger: "blur" }],
        mobile: [
          { required: true, message: "此项必填", trigger: "blur" },
          { validator: validate.vPhone, trigger: "blur" }
        ],
        deptId: [{ required: true, message: "此项必填", trigger: "change" }],
        timeId: [{ required: true, message: "此项必填", trigger: ["blur", "change"] }],
        doctorId: [{ required: true, message: "此项必填", trigger: "change" }],
        sourceName: [{ required: true, message: "此项必填", trigger: "change" }],
        sourceType: [{ required: true, message: "此项必填", trigger: "change" }]
      }
    };
  },
  mounted() {
    let th = this;
    th.getCommonConfigByKey("国籍").then(res => {
      th.nationalityEnum = res;
    });
    th.getCommonConfigByKey("预约类型").then(res => {
      th.reserveTypeArray = res;
    });
    th.getCommonConfigByKey("推荐来源").then(res => {
      th.sourceArray = res;
    });
    th.getCommonConfigByKey("职业").then(res => {
      th.occupationArray = res;
    });
    th.getCommonConfigByKey("民族").then(res => {
      th.nationArray = res;
    });
    th.getCommonConfigByKey("证件类型").then(res => {
      th.certificateTypeArray = res;
    });
    th.getCommonConfigByKey("机构推荐").then(res => {
      th.jgEnum = res;
    });
    th.getCommonConfigByKey("平台宣传").then(res => {
      th.ptEnum = res;
    });
    let patientId = th.$route.query.patientId;
    if (patientId) {
      th.form.patientId = Number.parseInt(th.jieMi(patientId));
    }
    th.getQuery();
  },
  activated() {
    const th = this;
    let patientId = th.$route.query.patientId;
    if (patientId) {
      patientId = Number.parseInt(th.jieMi(patientId));
      //判断是否同一患者
      if (patientId != th.form.patientId) {
        th.form.patientId = patientId;
        th.getQuery();
      }
    }
  },
  methods: {
    //推荐医生
    onTCDoctor(obj) {
      const th = this;
      th.form.sourceName = obj.trueName;
    },
    onSubmit() {
      let th = this;
      let j = {};
      let add = function() {
        th.showLoading();
        j.id = "";
        j.name = j.name.trim();
        th.$api.registerAddOrder(j).then(res => {
          if (res.executed) {
            th.$message.success("操作成功");
            th.formReset();
          } else {
            th.$message.error(res.message);
          }
          th.showLoading(false);
        });
      };
      let update = function() {
        th.showLoading();
        th.$api.updateRegisterRecord(j).then(res => {
          if (res.executed) {
            th.$message.success("操作成功");
            th.formReset();
          } else {
            th.$message.error(res.message);
          }
          th.showLoading(false);
        });
      };
      th.$refs["form"].validate(v => {
        if (v) {
          const { smsSend } = this.form;
          Object.assign(j, th.form);
          j.smsSend = smsSend ? 1 : 0;
          delete j.areaArray;
          delete j.timeStr;
          th.form.areaArray.forEach((item, index) => {
            switch (index) {
              case 0:
                j.provinceId = item.adcode;
                j.province = item.name;
                break;
              case 1:
                j.cityId = item.adcode;
                j.city = item.name;
                break;
              case 2:
                j.districtId = item.adcode;
                j.district = item.name;
                break;
            }
          });
          if (typeof th.form.patientId != "number") {
            j.patientId = "";
          }
          let yyTypeData = th.reserveTypeArray.find(d => {
            return d.id == th.form.registerType;
          });
          if (yyTypeData) j.registerName = yyTypeData.desc;
          if (j.id) {
            update();
          } else {
            add();
          }
        }
      });
    },
    getQuery() {
      let th = this;
      th.form.id = "";
      if (th.form.patientId) {
        th.form.name = th.$route.query.name;
        th.getPatient(th.form.name);
        th.getPatientDetail(th.form.patientId);
      } else {
        th.getPatient();
      }
    },
    onConfirmTime(obj) {
      let th = this;
      th.form.timeId = obj.id;
      th.form.timeStr = `${obj.startTime}~${obj.endTime}`;
      th.$refs["form"].validateField("timeId");
      th.form.dateDay = obj.dateStr;
    },
    onOpenTime() {
      if (this.form.deptId && this.form.doctorId) {
        this.dialogTime = true;
      }
    },
    onBlurIdCard() {
      let th = this;
      if (!th.form.idCard) return;
      if (th.form.certificateType != 1) return;
      const fn = () => {
        let result = th.$utils.getIdCardInfo(th.form.idCard);
        th.form.birthday = result.birthday;
        th.form.sex = result.sex == "男" ? 1 : 2;
        th.form.age = th.$utils.getAgeToBirthday(result.birthday);
      };
      validate.vPeopleNumber(null, th.form.idCard, function(err) {
        if (typeof err == "undefined") {
          fn();
        }
      });
    },
    onClearPatient() {
      this.getPatient();
      this.formReset();
    },
    getPatient(name) {
      let th = this;
      let j = {
        hpId: th.adminUser.hpId,
        pageNum: 1,
        pageSize: 20,
        nameOrMobile: name
      };
      th.$api.getThePatientLibraryList(j).then(res => {
        if (res.executed) {
          th.patientArray = res.dataBody.list;
        }
      });
    },
    onOpenFile() {
      let th = this;
      th.$refs["oneImageUpload"].openFile();
    },
    formReset() {
      this.sourceObjList = [];
      this.$refs["form"].resetFields();
      this.form.head = "";
      this.form.timeStr = "";
      this.form.smsSend = false;
      this.form.smsVisitTime = "";
    },
    getPatientData() {
      let th = this;
      let j = {
        registerId: th.form.id
      };
      th.$api.getRegisterListInfo(j).then(res => {
        if (res.executed) {
          th.$utils.joinFormJson(th.form, res.dataBody.list[0]);
        }
      });
    },
    getPatientDetail() {
      let th = this;
      let j = {
        patientId: th.form.patientId,
        hpId: th.adminUser.hpId
      };
      th.$api.getThePatientLibraryById(j).then(res => {
        if (res.executed) {
          let data = res.thePatientLibraryDetail;
          th.$utils.joinFormJson(th.form, data);
          th.revertSource(data);
          if (data.provinceId) {
            th.form.areaArray = [
              { name: data.province, adcode: data.provinceId },
              { name: data.city, adcode: data.cityId },
              { name: data.district, adcode: data.districtId }
            ];
          }
        }
      });
    },
    revertSource(data) {
      this.sourceObjList = [];
      this.sourceObj = null;
      this.getRecommendDetailListByType({ type: "revert" });
    },
    onChangeBirthday() {
      let th = this;
      if (!th.form.birthday) return;
      th.form.age = th.$utils.getAgeToBirthday(th.form.birthday);
    },
    onChangeDept(value) {
      let th = this;
      th.form.doctorId = "";
      th.$nextTick(function() {
        th.$refs["doctorSearch"].onSearch();
      });
    },
    onChangePatient(value) {
      if (!value) return;
      if (typeof value != "number") {
        this.formReset();
        this.$nextTick(function() {
          this.form.name = value;
          this.form.patientId = value;
        });
        return;
      }
      this.getPatientDetail();
    },
    onChangeTJ() {
      this.form.sourceName = "";
      this.form.sourceCode = "";
      this.form.tjDoctorId = null;
      this.getRecommendDetailListByType({ type: "init" });
    },
    getRecommendDetailListByType({ type }) {
      let params = {
        hpId: this.adminUser.hpId,
        type: ""
      };
      if (this.form.sourceType != 1 && this.form.sourceType != 5 && this.form.sourceType != 6) {
        params.type = this.form.sourceType;
      }
      if (params.type) {
        this.$api
          .getRecommendDetailListByType({
            ...params
          })
          .then(res => {
            if (res.executed) {
              this.sourceObjList = res.dataBody;
              this.sourceObj = null;
              if (type && type === "revert") {
                this.sourceObj = this.sourceObjList.filter(obj => obj.id == this.form.sourceCode)[0];
              } else {
                this.form.sourceName = "";
                this.form.sourceCode = "";
              }
            }
          });
      }
    },
    onChangeSourceObj(obj) {
      this.form.sourceName = obj.name;
      this.form.sourceCode = obj.id;
    }
  },
  watch: {}
};
</script>
<style lang="scss" scoped>
.add-reserve {
  .user-head {
    border: 1px solid #eee;
    padding: 5px;
    img {
      width: 230px;
      display: block;
      height: 230px;
      object-fit: cover;
    }
  }
  .flex-gutter {
    h3 {
      margin-top: 5px;
    }
    display: flex;
    .flex-left {
      width: 520px;
      flex-shrink: 0;
    }
    .flex-right {
      padding-left: 30px;
      position: relative;
      width: 100%;
      overflow: hidden;
      &::before {
        width: 1px;
        height: 100%;
        background: #eee;
        content: "";
        position: absolute;
        top: 0;
        left: 15px;
      }
    }
    .el-form-item {
      margin-bottom: 5px;
    }
  }
}
</style>
